package com.example.music.ui.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.music.R
import com.example.music.ui.adapters.MusicAdapter

class LibraryFragment : BaseFragment() {
    
    private lateinit var musicAdapter: MusicAdapter
    
    override fun getLayoutRes(): Int = R.layout.fragment_library
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        observeViewModel()
        setupClickListeners()
    }
    
    private fun setupRecyclerView() {
        musicAdapter = MusicAdapter { music ->
            viewModel.playMusic(music)
        }
        
        val musicRecyclerView = view?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.musicRecyclerView)
        musicRecyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = musicAdapter
        }
    }
    
    private fun observeViewModel() {
        viewModel.musicList.observe(viewLifecycleOwner, Observer { musicList ->
            val libraryTitle = view?.findViewById<android.widget.TextView>(R.id.libraryTitle)
            val musicRecyclerView = view?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.musicRecyclerView)
            val emptyState = view?.findViewById<android.widget.LinearLayout>(R.id.emptyState)
            
            libraryTitle?.text = "音乐库 (${musicList.size})"
            
            if (musicList.isEmpty()) {
                musicRecyclerView?.visibility = View.GONE
                emptyState?.visibility = View.VISIBLE
            } else {
                musicRecyclerView?.visibility = View.VISIBLE
                emptyState?.visibility = View.GONE
                musicAdapter.updateMusicList(musicList)
            }
        })
        
        viewModel.currentMusic.observe(viewLifecycleOwner, Observer { currentMusic ->
            musicAdapter.setCurrentMusic(currentMusic)
        })
    }
    
    private fun setupClickListeners() {
        val sortButton = view?.findViewById<android.widget.ImageButton>(R.id.sortButton)
        sortButton?.setOnClickListener {
            // TODO: 实现排序功能
        }
    }
}
